<?php
namespace app\controller;
use app\BaseController;
use think\Request;
use app\validate\Register;
use app\validate\Login;
use think\console\command\make\Model;
use think\exception\ValidateException;
use app\model\UserUser;
use app\model\AdminUser;
use app\model\AdminPermission;
use app\controller\Db;
class Index extends BaseController
{   
    protected $user;
    protected $admin;
    protected $permission;
    public function __construct()
    {
        $this->user = new UserUser();
        $this->admin = new AdminUser();
         $this->permission = new AdminPermission();
    }
    /*
    生成token令牌
    */
    protected function createToken(){
        $str= sha1(md5(uniqid(md5(microtime(true)), true)));
        return $str;
    }   
    /*
    检查token且是否过期
    */
    protected function checkToken($token)
    { 
       try{
            $token_out=$this->user->where('token',$token)->value('token_out');
           if(!isset($token_out)){
                throw new \Exception("token不存在");
           }
           if($token_out-time()<=0){
             
                throw new \Exception("token已经过期，请重新登陆");
            }
            return [
                'code'=>'200',
                'msg'=>"success",
                'token_out'=> $token_out
            ];      
       }catch(\Exception $e){
            return  [
                'code' => '400',
                'msg' => $e->getMessage(),
            ];
       }
    }
    /*
    检查后台账号token且是否过期
    */
    protected function AdminCheckToken($token)
    { 
       try{
            $data=$this->admin->where('token',$token)->find();
           if(!isset($data)){
                throw new \Exception("token不存在");
           }
           if($data->token_out-time()<=0){
             
                throw new \Exception("token已经过期，请重新登陆");
            }
            return [
                'code'=>'200',
                'msg'=>"success",
                'token_out'=> $data->token_out,
                'id'=>$data->id
            ];      
       }catch(\Exception $e){
            return  [
                'code' => '400',
                'msg' => $e->getMessage(),
            ];
       }
    }
    /*
    刷新token接口
    */
    public function refreshToken($token)
    {
        try{
            $time = time() + 86400;
            $token_out = $this->user->where('token', $token)->update(['token_out'=> $time,]);
            if (!$token_out) {
                throw new \Exception("token不存在");
            }
            return json([
                'code' => '200',
                'msg' => '令牌时间刷新成功',
                'token_out' => $time
            ]);
        }catch(\Exception $e){
            return json([
                'code' => '400',
                'msg' =>$e->getMessage(),
            ]);
        }    
    }
    /*
    注册账号接口
    */
    public function register(Request $request)
    {
        $data = $request->param();
        try {
            validate(Register::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  json([
                'code'=>400,
                'msg'=>$e->getError()
            ]);
        }
        return $this->user->userCreate($data);
    }
    /*
    登陆接口
    */
    public function login(Request $request)
    {
        $data = $request->param();
        try {
            validate(Login::class)->scene('user')->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  json(
                ['code' => 400,
                '错误' => $e->getError()
            ]);
        }
        $data['token'] = $this->createToken();
        $data['token_out'] = time() + 86400;
        return $this->user->userLogin($data); 
    }
    /*
    后台登陆接口
    */
    public function adminLogin(Request $request)
    {
        $data = $request->param();
        try {
            validate(Login::class)->scene('admin')->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  json(
                ['code' => 400,
                '错误' => $e->getError()
            ]);
        }
        $data['token'] = $this->createToken();
        $data['token_out'] = time() + 86400;
        return $this->admin->userLogin($data); 
    }
    //令牌验证登陆接口（后台）
    public function getAdminLogin(Request $request)
    {
        $data = $request->param();
        return $this->admin->getLogin($data['token']); 
    }
    //
    public function  adminLogout(){
       return json([
                'code'=>20000,
                'data'=>"success"
           ]);
    }
    //
    public function routes(Request $request){
         $data = $request->param();
         dump($data);
           return json([
                'code'=>20000,
                'data'=>[
                        'path'=>'/panpan',
                        "component"=>"layout/Layout",
                        'redirect'=> '/panpan/index',
                        "children"=>[
                                'path'=>'index',
                                'component'=>'/views/interface/index',
                                 'name'=>'panpan',
                                 'meta'=>[
                                            'title'=> '测试',
                                            'icon'=> 'dashboard',
                                            'affix'=> 'true'
                                     ]
                            ]
                        
                    ]
           ]);
    }
    /*
    登出接口
    */
    public function  logout(){
        session_id() || @session_start();
        if(isset($_SESSION['userData'])){
            $_SESSION['userData'] = null;
        }
       return json([
                'code'=>'200',
                'msg'=>"success",
           ]);
    }
    
    /*
      个人中心接口
    */
    public function  avatar()
    {
    
        $files= request()->file();
        $data = request()->param();
        try {
            $res = $this->checkToken($data['token']);
            if ($res['code'] == 400) {
                return json($res);
            }
            validate(Register::class)->scene('edit')->check($data);
            if(!isset($files)){
                return  $this->user->avatar($data,false);
            }
            validate(['image' => 'filesize:204800|fileExt:jpg'])
            ->check($files);
            validate(Register::class)->scene('edit')->check($data);
            foreach ($files as $file) {
             $savename[] = \think\facade\Filesystem::disk('public')->putFile('topic', $file);
            }
            $data['image'] = 'http://test.panview.cn/tp/public/storage/' . $savename[0];
            return  $this->user->avatar($data,true);
        } catch (ValidateException $e) {
           return json([
               'code'=>400,
               'msg'=>$e->getError()
           ]); 
        }
      
    }
    //
    public function getAdminUser(){

        return  $this->admin->getAdminUser();
    }
    //注册后台账号
    public function registerAdminUser(Request $request){
        $data = $request->param();
        try {
            validate(Login::class)->scene('admin')->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  json(
                ['code' => 400,
                '错误' => $e->getError()
            ]);
        }
        return  $this->admin->registerAdminUser($data);
    }
        /*
        获取权限列表
        */
    public function   getPermission(Request $request){
        $data = $request->param();
        $res = $this->AdminCheckToken($data['token']);
        if ($res['code'] == 400) {
                return json($res);
            }
         return  $this->permission->getPermission();
    }
   /*
        获取权限列表2
        */
    public function   getInPermission(Request $request){
        $arr=[];
        $arr2=[];
        $data = $request->param();
        $res= $this->admin->find($data['id']);
        $res2=$res->adminUserPermission;
        foreach ( $res2 as $role) {
        	// 输出用户的角色名
        	$arr[]=$role->p_key;
        }
        $arr2[$res['username']]=$arr;
        return json([
                'code'=> 20000,
                'data'=>$arr2
            ]);
    }
    //获取某个后台账号的权限key
    public function getUserPermission(){
       $data=$this->admin->select()->toArray();
       $arr=[];
       $arr2=[];
       foreach ($data as $res){
           $resdata=$this->admin->permission($res['id']);
           foreach ( $resdata as $role) {
        	// 输出用户的角色名
        	$arr2[]=$role->p_key;
        }
           $arr[$res['username']]=$arr2;
           $arr2=[];
       }
        return json([
                'code'=> 20000,
                'data'=>$arr
            ]);
   
  
    }
    //
    public function updateUserPermission(Request $request){
        $data = $request->param();
        $data2=explode(',',$data['data']);
        $arr=[];
        $resdata=$this->admin->permission($data['id']);
        foreach ( $resdata as $role) {
        	// 输出用户的角色名
        	$arr[]=$role->p_key;
        }
       
        $res=array_diff($arr,$data2);
        if(count($res)!==0){
            $p1=$this->permission->where('p_key','in',$res)->column('id');
            $this->admin->find($data['id'])->adminUserPermission()->detach($p1);
        }
        $res2=array_diff($data2,$arr);
        if(count($res2)!==0){
            $p2=$this->permission->where('p_key','in',$res2)->column('id');
            $this->admin->find($data['id'])->adminUserPermission()->saveAll($p2);
        }
        // $msg= $this->permission->getPermissionPan();
        // return json([
        //         'code'=>20000,
        //         'data'=>$msg
        //     ]);
         return json([
                'code'=>20000
                
            ]);
    }

}
